package com.dmooo.yxmmerchant.view.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.common.dialog.MyDialog;
import com.common.util.SPUtils;
import com.common.util.StartActivityUtil;
import com.common.util.ToastUtil;
import com.dmooo.yxmmerchant.R;
import com.dmooo.yxmmerchant.base.BaseActivity;
import com.dmooo.yxmmerchant.common.Config;
import com.hjq.permissions.Permission;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;

import butterknife.BindView;
import butterknife.OnClick;

public class ChatActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView txtTitle;
    @BindView(R.id.tv_right)
    TextView tv_right;

    @Override
    protected int getLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initEventAndData() {
        txtTitle.setText(getIntent().getExtras().getString("name"));

//        tv_right.setVisibility(View.VISIBLE);
        if(getIntent().getExtras().getString("type")!=null){
            findViewById(R.id.btn_zhuan).setVisibility(View.GONE);
        }
        EaseChatFragment chatFragment = new EaseChatFragment();
        chatFragment.hideTitleBar();
        chatFragment.setChatFragmentHelper(new EaseChatFragment.EaseChatFragmentHelper() {
            @Override
            public void onSetMessageAttributes(EMMessage message) {
                // 通过扩展属性，将userPic和userName发送出去。
                message.setAttribute("avatar", "");
                message.setAttribute("nick", SPUtils.get(mContext,Config.ADMIN_NAME,"客服").toString());
                message.setAttribute("nickto",getIntent().getExtras().getString("name"));
                message.setAttribute("avatarto","");
            }

            @Override
            public void onEnterToChatDetails() {

            }

            @Override
            public void onAvatarClick(String username) {
                if(username.startsWith("user")){
                    Bundle bundle=new Bundle();
                    bundle.putString("uid",username.replace("user",""));
                    StartActivityUtil.startActivity(ChatActivity.this,UserInfoActivity.class,bundle);
                }
//                startActivity(new Intent(GroupChatActivity.this,StuPicActivity.class).putExtra("uid",username));
            }

            @Override
            public void onAvatarLongClick(String username) {

            }

            @Override
            public boolean onMessageBubbleClick(EMMessage message) {
                if(message.getType()==EMMessage.Type.TXT){
                    EMTextMessageBody body= (EMTextMessageBody) message.getBody();
                    if(body.getMessage().contains("goods_id/")){
                        Bundle bundle=new Bundle();
                        bundle.putString("goods_id",body.getMessage().substring(body.getMessage().indexOf("goods_id/"),body.getMessage().length()).replace("goods_id/",""));
//                        StartActivityUtil.startActivity(ChatActivity.this,MallGoodsDetailActivity.class,bundle);
                    }else if(body.getMessage().contains("service_id/")){
//                        Bundle bundle=new Bundle();
//                        bundle.putString("service_id",body.getMessage().substring(body.getMessage().indexOf("service_id/"),body.getMessage().length()).replace("service_id/",""));
//                        StartActivityUtil.startActivity(ChatActivity.this,ServiceDetailActivity.class,bundle);
                    }
                }
                return false;
            }

            @Override
            public void onMessageBubbleLongClick(EMMessage message) {

            }

            @Override
            public boolean onExtendMenuItemClick(int itemId, View view) {
                return false;
            }

            @Override
            public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
                return null;
            }
        });
        Bundle args = new Bundle();
        args.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        args.putString(EaseConstant.EXTRA_USER_ID, getIntent().getExtras().getString("uuid"));
        chatFragment.setArguments(args);
        getSupportFragmentManager().beginTransaction().add(R.id.ll_container, chatFragment).commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!checkPermission(Permission.READ_PHONE_STATE)) {
            requestPermission(Permission.READ_PHONE_STATE, "手机存储权限");
            return;
        }
        if (!checkPermission(Permission.WRITE_EXTERNAL_STORAGE)) {
            requestPermission(Permission.WRITE_EXTERNAL_STORAGE, "手机存储权限");
            return;
        }
        if (!checkPermission(Permission.CAMERA)) {
            requestPermission(Permission.CAMERA, "拍照权限");
            return;
        }
        if (!checkPermission(Permission.ACCESS_FINE_LOCATION)) {
            requestPermission(Permission.CAMERA, "定位权限");
            return;
        }
        if (!checkPermission(Permission.ACCESS_COARSE_LOCATION)) {
            requestPermission(Permission.CAMERA, "定位权限");
            return;
        }
    }

    @Override
    protected void createPresenter() {

    }

    @OnClick({R.id.tv_left, R.id.btn_zhuan,R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_left:
                finish();
                break;
            case R.id.btn_zhuan:
                StartActivityUtil.startActivityForResultByA(this, SelKfActivity.class, new Bundle(), 1000);
                break;
            case R.id.tv_right:
                Intent intent=new Intent(ChatActivity.this,SettingActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void show(String uuid, String name, String avatar) {
        MyDialog.showMaterialDialog(getSupportFragmentManager(), "转接提示", "确定将该用户转接给客服" + name + "吗?", "取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }, "确定转接", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zhuan(uuid,name,avatar);
            }
        }).show();
    }

    private void zhuan(String uuid, String name, String avatar) {
        EMMessage message = EMMessage.createTxtSendMessage("您自动被转接给客服"+name, getIntent().getExtras().getString("uuid"));
        message.setAttribute("avatar", "");
        message.setAttribute("nick", Config.ADMIN_NAME);
        message.setAttribute("b_nick", name);
        message.setAttribute("uuid", uuid);
        message.setAttribute("b_avatar", avatar);
        message.setChatType(EMMessage.ChatType.Chat);
        EMClient.getInstance().chatManager().sendMessage(message);
        message.setMessageStatusCallback(new EMCallBack(){
            @Override
            public void onSuccess() {
                finish();
            }

            @Override
            public void onError(int code, String error) {
                ToastUtil.getInstance().showErrorMsg("转接失败");
            }

            @Override
            public void onProgress(int progress, String status) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1000) {
                Log.d("dsfasdf", data.getStringExtra("uuid"));
                Log.d("dsfasdf", data.getStringExtra("nick"));
                Log.d("dsfasdf", data.getStringExtra("avatar") + "");
                show(data.getStringExtra("uuid"), data.getStringExtra("nick"), data.getStringExtra("avatar") + "");
            }
        }
    }
}
